<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Article List</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .article {
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .article h2 {
            margin-top: 0;
        }
        .buttons {
            margin-top: 10px;
        }
        .buttons button {
            padding: 5px 10px;
            margin-right: 10px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .buttons button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Article List</h1>
        <p>Welcome, <span id="username">{{.username}}</span>!</p>
        <button class="external-button" onclick="goToPublishBlog()">Go to PublishBlog</button>
        <div id="article-list">
            {{range .articles}}
            <div class="article">
                <h2>{{.Title}}</h2>
                <p>{{.Content}}</p>
                <div class="stats">
                    <span>Likes: <span id="likes-{{.ID}}">{{.Likes}}</span></span>
                    <span>Favorites: <span id="favorites-{{.ID}}">{{.Favorites}}</span></span>
                </div>
                <div class="buttons">
                    <button onclick="likeArticle('{{.ID}}')">Like</button>
                    <button onclick="favoriteArticle('{{.ID}}')">Favorite</button>
                    <button onclick="deleteArticle('{{.ID}}')">Delete</button>
                </div>
                <div class="comment-section">
                    <input type="text" id="comment-input-{{.ID}}" placeholder="Add a comment">
                    <button onclick="postComment('{{.ID}}')">Post</button>
                </div>
                <div class="comments" id="comments-{{.ID}}">
                    <!-- Comments will be appended here -->
                </div>
            </div>
            {{end}}
        </div>
    </div>

    <script>
        function goToPublishBlog() {
            const username = document.getElementById('username').textContent;
            window.location.href = `http://127.0.0.1:8866/publish?username=${username}`;
        }

        function deleteArticle(articleId) {
            fetch(`/article/${articleId}/delete`, {
                method: 'POST'
            })
           .then(response => response.json())
           .then(data => {
                alert('Article liked: ' + JSON.stringify(data));
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        function likeArticle(articleId) {
            fetch(`/article/${articleId}/like`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                alert('Article liked: ' + JSON.stringify(data));
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        function favoriteArticle(articleId) {
            fetch(`/article/${articleId}/favorite`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                alert('Article favorited: ' + JSON.stringify(data));
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        function postComment(articleId) {
            const commentInput = document.getElementById(`comment-input-${articleId}`);
            const commenttext = commentInput.value;
            const username = document.getElementById('username').textContent;

            if (commenttext.trim() === "") {
                alert("Comment cannot be empty");
                return;
            }

            fetch(`/article/${articleId}/publishcomment`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, commenttext })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'Comment posted') {
                    const commentsDiv = document.getElementById(`comments-${articleId}`);
                    const newCommentDiv = document.createElement('div');
                    newCommentDiv.className = 'comment';
                    newCommentDiv.textContent = `${data.comment.username}: ${data.comment.text}`;
                    commentsDiv.appendChild(newCommentDiv);
                    commentInput.value = ""; // Clear the input field
                } else {
                    alert('Failed to post comment: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    </script>
</body>
</html>